<!doctype html>
<html>
    <head>
        <title>情报站</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />

        <!-- ✅ 正确的 Tailwind 和 DaisyUI CDN -->
        <script src="https://cdn.tailwindcss.com"></script>
        <link
            href="https://cdn.jsdelivr.net/npm/daisyui@4.12.14/dist/full.min.css"
            rel="stylesheet"
            type="text/css"
        />
    </head>
    <body>
        <main class="container m-auto">
            <div
                class="flex flex-row justify-center-safe item-center mt-5 sm:mt-2 md:mt-2"
            >
                <div class="basis-1/4">
                    <h2 class="font-bold text-xl">今日情报站</h2>
                    <p class="text-md" id="date"></p>
                    <p class="text-md" id="weekday"></p>
                </div>
                <div class="basis-3/4 flex flex-row justify-around">
                    <div id="market_start_e">
                        <h2 class="font-bold text-lg">开市</h2>
                        <label class="font-bold text-lg" id="market_start"
                            >0</label
                        >
                    </div>
                    <div id="market_noon_e">
                        <h2 class="font-bold text-lg">午市</h2>
                        <label class="font-bold text-lg" id="market_noon"
                            >0</label
                        >
                    </div>
                    <div id="market_end_e">
                        <h2 class="font-bold text-lg">休市</h2>
                        <label class="font-bold text-lg" id="market_end"
                            >0</label
                        >
                    </div>
                    <div class="flex flex-row justify-center-safe my-4">
                        <button
                            class="btn btn-sm mx-1"
                            onclick="fetchStockInfo('before'); fetchNewByFlat('before')"
                        >
                            <svg
                                class="h-6 w-6 fill-current md:h-8 md:w-8 rtl:rotate-180"
                                xmlns="http://www.w3.org/2000/svg"
                                width="24"
                                height="24"
                                viewBox="0 0 24 24"
                            >
                                <path
                                    d="M15.41,16.58L10.83,12L15.41,7.41L14,6L8,12L14,18L15.41,16.58Z"
                                ></path>
                            </svg>
                        </button>
                        <button
                            class="btn btn-sm mx-1"
                            onclick="fetchStockInfo('after'); fetchNewByFlat('after')"
                        >
                            <svg
                                class="h-6 w-6 fill-current md:h-8 md:w-8 rtl:rotate-180"
                                xmlns="http://www.w3.org/2000/svg"
                                width="24"
                                height="24"
                                viewBox="0 0 24 24"
                            >
                                <path
                                    d="M8.59,16.58L13.17,12L8.59,7.41L10,6L16,12L10,18L8.59,16.58Z"
                                ></path>
                            </svg>
                        </button>
                    </div>
                </div>
            </div>
            <div class="divider"></div>
            <ul
                class="timeline timeline-snap-icon max-md:timeline-compact timeline-vertical"
                id="news"
            ></ul>

            <!-- Open the modal using ID.showModal() method -->

            <dialog id="error_modal" class="modal">
                <div class="modal-box">
                    <h3 class="text-lg font-bold">哎呀，真糟糕!</h3>
                    <p class="py-4" id="errorMsg"></p>
                    <div class="modal-action">
                        <form method="dialog">
                            <!-- if there is a button in form, it will close the modal -->
                            <button class="btn">关闭</button>
                        </form>
                    </div>
                </div>
            </dialog>
        </main>

        <script>
            async function fetchIndex(date) {
                try {
                    const res = await fetch("/market/stock/" + date); // 假设后端提供这个接口
                    console.log("Response:", res);

                    if (!res.ok) {
                        // 尝试从响应中获取错误信息
                        const errorData = await res.json();
                        throw new Error(
                            errorData.message ||
                                `HTTP error! status: ${res.status}`,
                        );
                    }

                    const result = await res.json();
                    console.log("API Response:", result);

                    // 根据您的后端 Output<Vec<News>> 结构处理响应
                    if (result.status_code === 200 && result.data !== null) {
                        displayIndex(result.data); // result.data 是新闻数组
                    } else {
                        throw new Error(result.message || "No data available");
                    }
                } catch (error) {
                    console.error(error);
                    document.getElementById("errorMsg").innerText =
                        error.message || "获取股市指数失败！";
                    error_modal.showModal();
                }
            }

            async function fetchNews(date) {
                try {
                    const res = await fetch("/market/news/date/" + date);
                    console.log("Response:", res);

                    // 修正条件判断：使用 res.ok 或正确比较状态码
                    if (!res.ok) {
                        // 尝试从响应中获取错误信息
                        const errorData = await res.json();
                        throw new Error(
                            errorData.message ||
                                `HTTP error! status: ${res.status}`,
                        );
                    }

                    const result = await res.json();
                    console.log("API Response:", result);

                    // 根据您的后端 Output<Vec<News>> 结构处理响应
                    if (result.status_code === 200 && result.data !== null) {
                        displayNews(result.data); // result.data 是新闻数组
                    } else {
                        throw new Error(result.message || "No data available");
                    }
                } catch (error) {
                    console.error("Error fetching news:", error);
                    document.getElementById("errorMsg").innerText =
                        "糟糕，获取情报失败！错误: " + error.message;
                    // 确保 error_modal 已定义
                    if (
                        typeof error_modal !== "undefined" &&
                        error_modal.showModal
                    ) {
                        error_modal.showModal();
                    }
                }
            }

            async function fetchNewByFlat(flat) {
                let current_date = document.getElementById("date").innerText;
                if (!current_date) {
                    document.getElementById("errorMsg").innerText =
                        "很抱歉，无法获取当前查询日期！";
                    error_modal.showModal();
                    return;
                }
                if ("before" === flat) {
                    let date_before = new Date(current_date);
                    date_before.setDate(date_before.getDate() - 1);
                    await fetchNews(date_before.toISOString().split("T")[0]);
                } else if ("after" === flat) {
                    if (
                        current_date === new Date().toISOString().split("T")[0]
                    ) {
                        document.getElementById("errorMsg").innerText =
                            "很抱歉，无法获取未来日期的新闻！";
                        error_modal.showModal();
                        return;
                    }
                    let date_after = new Date(current_date);
                    date_after.setDate(date_after.getDate() + 1);
                    await fetchNews(date_after.toISOString().split("T")[0]);
                }
            }

            async function fetchStockInfo(flag) {
                try {
                    let date = document.getElementById("date").innerText;
                    if (!date) {
                        document.getElementById("errorMsg").innerText =
                            "很抱歉，无法获取当前查询日期！";
                        error_modal.showModal();
                        return;
                    }

                    const res = await fetch(
                        "/market/stock/" + date + "/" + flag,
                    );
                    console.log("Response:", res);

                    // 修正条件判断：使用 res.ok 或正确比较状态码
                    if (!res.ok) {
                        // 尝试从响应中获取错误信息
                        const errorData = await res.json();
                        throw new Error(
                            errorData.message ||
                                `HTTP error! status: ${res.status}`,
                        );
                    }

                    const result = await res.json();
                    console.log("API Response:", result);

                    // 根据您的后端 Output<Vec<News>> 结构处理响应
                    if (result.status_code === 200 && result.data !== null) {
                        displayIndex(result.data); // result.data 是新闻数组
                    } else {
                        throw new Error(result.message || "No data available");
                    }
                } catch (error) {
                    console.error(error);
                    document.getElementById("errorMsg").innerText =
                        error.message || "获取股市指数失败！";
                    error_modal.showModal();
                }
            }

            //设置指数
            function displayIndex(indexs) {
                if (!indexs) {
                    document.getElementById("errorMsg").innerText =
                        "真糟糕，没有成功获取股市指数！";
                    error_modal.showModal();
                    return;
                }

                const indexArray = [
                    indexs.index_at_last_day,
                    indexs.index_at_start,
                    indexs.index_at_noon,
                    indexs.index_at_end,
                ];
                if (indexArray.length !== 4) {
                    document.getElementById("errorMsg").innerText =
                        "数据格式错误！";
                    error_modal.showModal();
                    return;
                }

                const [last, start, noon, end] = indexArray.map(Number);

                // 先设置文本
                document.getElementById("market_start").innerText = start;
                document.getElementById("market_noon").innerText = noon;
                document.getElementById("market_end").innerText = end;
                document.getElementById("date").innerText = indexs.date;

                // 再根据比较设置颜色, 今日指数的颜色全部对比开始的值
                setFontColor("market_start", last, start);
                setFontColor("market_noon", start, noon);
                setFontColor("market_end", start, end);
            }

            function displayNews(news) {
                if (news === null || news === undefined) {
                    document.getElementById("errorMsg").innerText =
                        "真抱歉，获取情报失败！";
                    error_modal.showModal();
                    return;
                }
                if (news.length < 1) {
                    document.getElementById("errorMsg").innerText =
                        "嗯？不知道请求失败还是up主还没有添加数据，过一段时间再看吧！";
                    error_modal.showModal();
                    return;
                }

                const count = news.length;
                let newsElement = document.getElementById("news");
                var newItems = "";
                var timelineClass = "timeline-start";
                var hrElement = "<hr/>";
                for (var i = 0; i < count; i++) {
                    var newsItem = news[i];
                    if (newsItem.country === "CN") {
                        timelineClass = "timeline-start mb-10 md:text-end";
                    } else {
                        timelineClass = "timeline-end mb-10 ";
                    }
                    if (i === count - 1) {
                        hrElement = "";
                    }
                    newItems +=
                        `<li>
                            <div class="timeline-middle">
                            <svg
                                xmlns="http://www.w3.org/2000/svg"
                                viewBox="0 0 20 20"
                                fill="currentColor"
                                class="h-5 w-5"
                            >
                                <path
                                fill-rule="evenodd"
                                d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z"
                                clip-rule="evenodd"
                                />
                            </svg>
                            </div>
                            <div class="` +
                        timelineClass +
                        `">
                         <div class="timeline-box">
                            <div class="text-lg font-black">` +
                        newsItem.title +
                        `</div>   </div>` +
                        newsItem.content +
                        `</div>` +
                        hrElement +
                        `</li>`;
                    newsElement.innerHTML = newItems;
                }
            }

            function setFontColor(elementId, prevIndex, currentIndex) {
                const el = document.getElementById(elementId);
                el.classList.remove("text-red-500", "text-green-500");

                if (currentIndex > prevIndex) {
                    el.classList.add("text-red-500"); // 上涨红色
                } else if (currentIndex < prevIndex) {
                    el.classList.add("text-green-500"); // 下跌绿色
                }
                // 相等则无颜色
            }

            function getWeekDay(date) {
                const days = [
                    "星期日",
                    "星期一",
                    "星期二",
                    "星期三",
                    "星期四",
                    "星期五",
                    "星期六",
                ];
                document.getElementById("weekday").textContent =
                    days[date.getDay()];
            }

            let date = new Date();
            getWeekDay(date);
            let formattedDate = date.toLocaleDateString().replace(/\//g, "-");
            document.getElementById("date").textContent = formattedDate;
            fetchNews(formattedDate);
            fetchIndex(formattedDate);
        </script>
    </body>
</html>
